package cn.edkuir.seckill.scheduled;

import cn.edkuir.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的定时上架
 * 每天晚上3点, 上架最近三天需要秒杀的商品
 */
@Service
@Slf4j
public class SeckillSkuScheduled {
    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedissonClient redissonClient;

    private final String UPLOAD_LOCK = "seckill:upload:lock";


    //上架最近三天的秒杀商品
    @Scheduled(cron = "0 * * * * ?")
    public void uploadSeckillSkuL3Days() {
        //分布式锁, 防止多台机器商品重复上架
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        log.info("定时任务触发");

        try {
            seckillService.uploadSeckillSku();
        } finally {
            lock.unlock();
        }
    }

}
